const Koa = require("koa");
const Router = require("@koa/router");
const cors = require("koa-cors");
const AlipaySdk = require('alipay-sdk').default;
const axios = require("axios");


const app = new Koa();
const router = new Router();
app.use(cors());
app.use(router.routes());

const alipaySdk = new AlipaySdk({
    appId: '9021000122680668', // 应用id
    signType: "RSA2",
    gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
    // keyType: 'PKCS1', // 默认值。请与生成的密钥格式保持一致，参考平台配置一节
    privateKey: "MIIEogIBAAKCAQEAhtUPS8caNrFjgGJ61r3XhAZFMN6TsnyVhLdnlKdgry1m7rG6lmhIo9SDkQrzs85RcjUc/en0cgwmGHSsQJ81GMmdLqIsWsCVuDwH6jlBcYApC5BNn94I993r+yW1rRb+AIJ5+l6ddyDjQDxjwUITTQjW/BSVpjwId0J6utNFODkOEVl0ZDSnnxLxpj+b4scLDvo0RhfCZP+fGPFkGyDHAKOp4gOf9RtU0raxG3DfeARHEYMBAiQ93Q4J5SB5gyMx2q4+PXCZ4Gdhm/nBVXgrFIMuM8zac8TvipG4+O32Gx0jw6goGp0rjDrmTkkjIeP2lJhxMtHBalznWDhhjhCAfwIDAQABAoIBADgCWZBI7QK7PXIfdpet1NDrKeLbEs+aISI4bba6sNcULSYKfk/skgA8T0r5GbMfiYW/uoNfpEOb+FdAYC2X9R6O4dR1Wad5SLh3d3I8xoq3ilVbZGN8gI02isiRKZ71Zh4gFTuEAjVyW/RbIbUuFYZynZupkWC0n2+rFgB1stNfhVFw6grAuxtlfsOE6SdLVqvnpxfzv/feKDlgRXSWJ98FGAr0zik2nfVYjoHTGqHO/4DVpyp9VNhDJ8VyG/hNqiooKLqmfkBn7HDPa13v3WK1YmnHLtYUmKvree6QY3mqyuJjMLn3q/CetKNe+zBTKzd6yL+Bf/iwzwdDoptMFEECgYEAx4IN2DYhrdW+jpvCBeDaiyY15lHzjdnqmwOP0vXcY7GnQOGcN0A1hkxuumOHGttWxVpb2jzFTrNjqXfrglT95Wz8ccMjK3wUCHMu7b+ZmXV2F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yMx2q4+PXCZ4Gdhm/nBVXgrFIMuM8zac8TvipG4+O32Gx0jw6goGp0rjDrmTkkjIeP2lJhxMtHBalznWDhhjhCAfwIDAQAB",// 公钥
});


router.get("/api/askStatus", async ctx => {
    //  生成链接  然后发送请求 查询验证码
    const { trade_no } = ctx.query;
    const bizContent = {
        out_trade_no: trade_no, // 订单号
        product_code: "FAST_INSTANT_TRADE_PAY", // 产品号
    };
    const result = alipaySdk.pageExec('alipay.trade.query', {
        method: 'GET',
        bizContent, // 订单信息
        // returnUrl: 'http://localhost:3000' // 回调地址
    });
    const payResult = await axios.get(result);
    if(payResult.status === 200){
        const { data } = payResult;
        const { trade_status } = data.alipay_trade_query_response;
        switch(data.status) {
            case "10000":
                switch(trade_status){
                    case "WAIT_BUYER_PAY":
                        ctx.body = {
                            code:1,
                            trade_status,
                            msg:"交易创建，等待买家付款"
                        };
                    break;
                    case "TRADE_CLOSED":
                        ctx.body = {
                            code:1,
                            trade_status,
                            msg:"未付款交易超时关闭，或支付完成后全额退款"
                        };
                    break;
                    case "TRADE_SUCCESS":
                        ctx.body = {
                            code:1,
                            trade_status,
                            msg:"交易支付成功"
                        };
                    break;
                    case "TRADE_FINISHED":
                        ctx.body = {
                            code:1,
                            trade_status,
                            msg:"交易结束，不可退款"
                        };
                    break;
                };
            break;
            case "20000":
                ctx.body = {
                    code:0,
                    msg:"别请求了，服务暂不可用（业务系统不可用）"
                };
            break;
            case "20001":
                ctx.body = {
                    code:0,
                    msg:"授权权限不足"
                };
            break;
            case "40002":
                ctx.body = {
                    code:0,
                    msg:"参数缺少"
                };
            break;
            case "40004":
                ctx.body = {
                    code:0,
                    msg:"业务处理失败"
                };
            break;
            case "40005":
                ctx.body = {
                    code:0,
                    msg:"业务处理失败"
                };
            break;
            case "40006":
                ctx.body = {
                    code:0,
                    msg:"业务处理失败"
                };
            break;

        }
    }else{
        ctx.body = {
            code:0,
            msg:"查询失败"
        }
    }
})


router.get("/api/pay", async ctx => {
    //  生成订单
    const trade_no = Math.random().toString(16).slice(-10);
    const bizContent = {
        out_trade_no: trade_no, // 订单号
        product_code: "FAST_INSTANT_TRADE_PAY", // 产品号
        subject: "abc", // 标题
        body: "234", //关于商品的描述
        total_amount: "1" // 商品价格
    };

    //  带着订单号 带着商品信息 去支付
    const result = alipaySdk.pageExec('alipay.trade.page.pay', {
        method: 'GET',
        bizContent, // 订单信息
        returnUrl: 'http://localhost:3000' // 回调地址
    });
    if (result) {
        ctx.body = {
            code: 1,
            msg: "生成支付链接成功",
            result,
            trade_no
        }
    } else {
        ctx.body = {
            code: 0,
            msg: "生成支付链接失败",
            result
        }
    }
})




app.listen(9000, () => {
    console.log("port:9000")
})